package com.heima.selection.service.impl;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.heima.selection.core.exception.BusinessException;
import com.heima.selection.mapper.UserMapper;
import com.heima.selection.pojo.SysAuthToken;
import com.heima.selection.pojo.dto.UserLoginDto;
import com.heima.selection.pojo.entity.TbUser;
import com.heima.selection.service.UserService;
import com.heima.selection.utils.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

;

/**
 * @author YuanZiwen
 * @date 2025/6/22
 * @description UserServiceImpl
 */
@SuppressWarnings("all")
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, TbUser> implements UserService {

    @Override
    public SysAuthToken doLogin(UserLoginDto dto) {
        TbUser user = Db.getOne(new LambdaQueryWrapper<>(TbUser.class)
                .eq(TbUser::getUsername, dto.getUsername()));
        if (Objects.isNull(user)) {
            throw new BusinessException("用户不存在");
        }

        if (!PasswordUtil.matches(dto.getPassword(), user.getPassword())) {
            throw new BusinessException("密码错误");
        }
        SysAuthToken sysAuthToken = createToken(user);
        log.info("用户登录:{}", user.getUsername());
        return sysAuthToken;
    }


    /**
     * 生成Token
     *
     * @param user       用户
     * @param clientType client类型
     * @return {@code SysAuthToken}
     */
    private SysAuthToken createToken(TbUser user) {
        SaLoginModel saLoginModel = new SaLoginModel();
        saLoginModel.setExtra("userId", user.getId());
        saLoginModel.setExtra("phone", user.getPhone());
        saLoginModel.setExtra("username", user.getUsername());
        StpUtil.login(user.getId(), saLoginModel);
        String token = StpUtil.getTokenValue();
        long tokenTimeout = StpUtil.getTokenTimeout();
        SysAuthToken sysAuthToken = new SysAuthToken(user.getId(), user.getUsername(),user.getAvatar(), user.getPhone(), token, tokenTimeout);
        return sysAuthToken;
    }
}


